<?php

class PermissionsController extends CController {

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow',
                'actions' => array('index', 'create', 'update', 'admin', 'delete', 'up', 'down'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Permissions;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Permissions'])) {
            $model->attributes = $_POST['Permissions'];
            if ($model->save())
                $this->redirect(array('index'));
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Permissions'])) {
            $model->attributes = $_POST['Permissions'];

            if ($model->save())
                $this->redirect(array('admin'));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {

        // we only allow deletion via POST request
        $model = $this->loadModel($id);
        if($model->id){
                  $criteria = new CDbCriteria();
        $criteria->condition = 'parent=:parent';
        $criteria->params = array(':parent' => $model->id);
   
        $nodes = Permissions::model()->findAll($criteria);
        if($nodes) $nodes->deleteAll();
        $model->delete();    
        }
        
        else 
            throw new CHttpException(403, 'Home page can not be deleted');
        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

        $this->redirect(array('index'));
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Permissions');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
            'data' => $this->getTree()
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $this->actionIndex();
    }

    /**
     * Change model's position
     * @param integer the Id of the model
     */
    public function actionUp() {
        $id = $_GET['id'];
        $model = Permissions::model()->findByPk($id);
        $criteria = new CDbCriteria();
        $criteria->condition = 'parent=:parent and position < :position';
        $criteria->params = array(':parent' => $model->parent, ':position' => $model->position);
        $criteria->order = 'position DESC';
        $up_model = Permissions::model()->find($criteria);
        if (!isset($up_model->id))
            $this->redirect(array("index"));
        $buffer = $up_model->position;
        $up_model->position = $model->position;
        $model->position = $buffer;
        $up_model->save();
        $model->save();
        $this->redirect(array("index"));
    }

    public function actionDown() {
        $id = $_GET['id'];
        $model = Permissions::model()->findByPk($id);
        $criteria = new CDbCriteria();
        $criteria->condition = 'parent=:parent and position > :position';
        $criteria->params = array(':parent' => $model->parent, ':position' => $model->position);
        $criteria->order = 'position ASC';
        $up_model = Permissions::model()->find($criteria);
        if (!isset($up_model->id))
            $this->redirect(array("index"));
        $buffer = $up_model->position;
        $up_model->position = $model->position;
        $model->position = $buffer;
        $up_model->save();
        $model->save();
        $this->redirect(array("index"));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Permissions::model()->findByPk((int) $id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    private function getChild($parent_id) {
        $up = "<div   class='tlt mcrbtn uparrbtn fr'></div>";
        $down = "<div   class='tlt mcrbtn downarrbtn fr'></div>";
        $delete = "<div  onclick=\"return confirm('Remove Page?')\" class='tlt mcrbtn delete fr'></div>";
        $data = array();
        $criteria = new CDbCriteria();
        $criteria->condition = 'parent=:parent';
        $criteria->params = array(':parent' => $parent_id);
        $criteria->order = 'position ASC';
        $nodes = Permissions::model()->findAll($criteria);
        foreach ($nodes as $node) {
            $text = "<span id='node_$node->id'>" .
                    CHtml::link($node->title, array('update',
                        'id' => $node->id)) .
                    CHtml::link($delete, array('delete',
                        'id' => $node->id, 'drop' => 1)) .
                    CHtml::link($up, array('up',
                        'id' => $node->id)) .
                    CHtml::link($down, array('down',
                        'id' => $node->id)) .
                    '</span>';
            $data[] = array('text' => $text);
        }
        return $data;
    }

    private function getTree() {
        $up = "<div tlt='Поднять'  class='tlt mcrbtn uparrbtn fr'></div>";
        $down = "<div tlt='Снизить'  class='tlt mcrbtn downarrbtn fr'></div>";
        $delete = "<div tlt='Удалить' onclick=\"return confirm('Delete?')\" class='tlt mcrbtn delete fr'></div>";
        $data = array();
        $criteria = new CDbCriteria();
        $criteria->condition = 'parent=:parent';
        $criteria->params = array(':parent' => 0);
        $criteria->order = 'position ASC';
        $root_models = Permissions::model()->findAll($criteria);
        foreach ($root_models as $model) {
            if ($model->id != 0) {
                $text =
                        CHtml::link($model->title, array('update',
                            'id' => $model->id)) .
                        CHtml::link($delete, array('delete',
                            'id' => $model->id, 'drop' => 1)) .
                        CHtml::link($up, array('up',
                            'id' => $model->id)) .
                        CHtml::link($down, array('down',
                            'id' => $model->id));
            } else {
                $text = CHtml::link($model->title, array('update',
                            'id' => $model->id));
            }
            if ($model->id != 0) {
                $data[] = array('text' => $text,
                    'children' => $this->getChild($model->id));
            } else {
                $data[] = array('text' => $text);
            }
        }
        return $data;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'Permissions-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
